import { buttonVariants } from '@/lib/utils'
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
} from '@/components/ui/pagination'
import { Button } from '@/components/ui/button'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'

import type { PageChangeParams } from '@/types/table'

type PaginationProps = {
  className?: string
  pagination: {
    current: number,
    total: number,
    pageSize: number
  }
  onPageChange: (pageChangeParams: PageChangeParams) => void
}

export default function AppPagination({
  className,
  pagination: {
    current,
    total,
    pageSize
  },
  onPageChange,
}: PaginationProps): JSX.Element {

  const pages = Array.from({ length: Math.ceil(total / pageSize) }, (_, i) => i + 1)

  const hanldePageClick = (page: number): void => {
    onPageChange({ current: page, prevCurrent: current, pageSize })
  }

  return (
    <Pagination className={cn('justify-end pt-2', className)}>
      <PaginationContent>
        <PaginationItem>
          <PaginationLink className='border'>
            <Button
              aria-label="Go to previous page"
              variant="ghost"
              disabled={current === 1}
              onClick={() => hanldePageClick(current - 1)}
            >
              <ChevronLeft />
            </Button>
          </PaginationLink>
        </PaginationItem>

        {pages.map((page) => {
          const isActive = page === current
          return (
            <PaginationItem key={page}>
              <PaginationLink
                isActive={page === current}
                className={cn({
                  [buttonVariants({
                    variant: 'default',
                    className:
                      'hover:text-primary-foreground! shadow-none! dark:bg-primary dark:hover:bg-primary/90',
                  })]: isActive,
                  border: !isActive,
                })}
                onClick={() => hanldePageClick(page)}
              >
                {page}
              </PaginationLink>
            </PaginationItem>
          )
        })}

        <PaginationItem>
          <PaginationLink className='border'>
            <Button
              aria-label="Go to previous page"
              variant="ghost"
              disabled={current === 1}
              onClick={() => hanldePageClick(current - 1)}
            >
              <ChevronRight />
            </Button>
          </PaginationLink>
        </PaginationItem>
      </PaginationContent>
    </Pagination>
  )
}
